import wx
import qrcode
from io import BytesIO


class QRCodeApp(wx.Frame):
    def __init__(self, parent, title):
        super(QRCodeApp, self).__init__(parent, title=title, size=(400, 400))

        self.InitUI()
        self.Centre()
        self.Show()

    def InitUI(self):
        panel = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)

        # 创建输入框
        self.text_ctrl = wx.TextCtrl(panel)
        vbox.Add(self.text_ctrl, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=10)

        # 创建按钮
        qr_btn = wx.Button(panel, label='生成二维码')
        qr_btn.Bind(wx.EVT_BUTTON, self.generate_qr_code)
        vbox.Add(qr_btn, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=10)

        # 创建图片显示区域
        self.image = wx.StaticBitmap(panel)
        vbox.Add(self.image, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=10)

        panel.SetSizer(vbox)

    def generate_qr_code(self, event):
        text = self.text_ctrl.GetValue()
        qr = qrcode.QRCode()
        qr.add_data(text)
        qr.make(fit=True)
        img = qr.make_image(fill_color="black", back_color="white")

        # 将PIL图像转换为wxPython图像
        buffer = BytesIO()
        img.save(buffer, format='PNG')
        buffer.seek(0)
        wx_image = wx.Image(buffer, wx.BITMAP_TYPE_PNG)
        wx_bitmap = wx_image.ConvertToBitmap()

        # 显示二维码
        self.image.SetBitmap(wx_bitmap)
        self.Layout()


if __name__ == '__main__':
    app = wx.App()
    QRCodeApp(None, title='wxPython 二维码生成器')
    app.MainLoop()
